﻿using ThresholdAssistant.ConfigSdk;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;

namespace ThresholdAssistant.Http.Extensions
{
    /// <summary>
    /// 数据转换扩展类
    /// </summary>
    public static class DataConvertExtensions
    {
        /// <summary>
        /// 添加头部信息
        /// </summary>
        /// <param name="requestHaaders"></param>
        /// <param name="headers"></param>
        public static void AddHeaders(this HttpHeaders requestHaaders, Dictionary<string, string> headers)
        {
            requestHaaders.Clear();//清楚请求头
            requestHaaders.Add("User-Agent", "threshold/1.0");

            if (headers == null || !headers.Any())
            {
                return;
            }

            foreach (var header in headers)
            {
                if (requestHaaders.Contains(header.Key))
                {
                    continue;
                }
                requestHaaders.Add(header.Key, header.Value);
            }
        }

        /// <summary>
        /// 转换成Get请求的Url接口地址
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramters"></param>
        /// <returns></returns>
        public static string ToGetUrl(this string url, Dictionary<string, string> paramters)
        {
            var text = paramters.ToGetParamters();
            return $"{url.TrimEnd('?', '&', '=')}?{text}";
        }

        /// <summary>
        /// 转换成Get请求参数
        /// </summary>
        /// <param name="paramters"></param>
        /// <returns></returns>
        public static string ToGetParamters(this Dictionary<string, string> paramters)
        {
            string text = "";
            if (paramters == null || !paramters.Any())
            {
                return text;
            }

            foreach (KeyValuePair<string, string> paramter in paramters)
            {
                text += paramter.Key + "=" + paramter.Value + "&";
            }
            return text.TrimEnd('&');
        }
    }
}